import React, { memo, useRef, useEffect, useMemo, useCallback } from "react";
import { shallowEqual, useSelector, useDispatch } from "react-redux";

import MiniPlayer from "./child/miniPlayer";
import NormalPlayer from "./child/normalPlayer";
import PlayList from "./child/playList";
import { getPlayUrl } from "../../utils";
import { changePlaying } from "../../store/actionCreator";

const Player = () => {
  const dispatch = useDispatch();
  const audioRef = useRef(null);

  const {
    playlist,
    currentSong,
    isShowPlaylist,
    playingLineNum,
    isFullScreen,
    playing,
  } = useSelector(
    (state) => ({
      currentSong: state.getIn(["curSong"]),
      playlist: state.getIn(["playList"]),
      isShowPlaylist: state.getIn(["isShowPlayList"]),
      playingLineNum: state.getIn(["playingLineNum"]),
      isFullScreen: state.getIn(["isFullScreen"]),
      playing: state.getIn(["playing"]),
    }),
    shallowEqual
  );

  useEffect(() => {
    audioRef.current.src = getPlayUrl(currentSong.id);
    dispatch(changePlaying(true));
  }, [currentSong, dispatch]);

  useEffect(() => {
    if (playing) {
      console.log("play");
      audioRef.current.play();
    } else {
      console.log("paused");
      audioRef.current.pause();
    }
  }, [playing, audioRef]);

  const canplay = () => {
    console.log("canplay 装备好  是否播放");
  };
  const handleError = () => {
    console.log("handleError");
  };
  const handleEnd = () => {
    console.log("end");
    dispatch(changePlaying(false));
  };
  const handleTimeUpdate = (e) => {};
  const handlePlayMusic = useCallback(() => {
    dispatch(changePlaying(!playing));
  }, [dispatch, playing]);

  const info = useMemo(() => {
    if (!currentSong.id) {
      return {};
    }
    console.log(currentSong);
    const obj = {
      song: currentSong.name,
      singer: currentSong.ar[0].name,
      picUrl: currentSong.al.picUrl || "",
    };
    return obj;
  }, [currentSong]);

  const played = useMemo(() => playing, [playing]);

  return (
    <div style={{ display: playlist.length ? "block" : "none" }}>
      {/* <NormalPlayer
        playingLineNum={playingLineNum}
        isFullScreen={isFullScreen}
      /> */}

      {/* <PlayList currentSong={currentSong} isShowPlaylist={isShowPlaylist} />   */}
      <MiniPlayer
        info={info}
        playing={played}
        handlePlayMusic={handlePlayMusic}
        isFullScreen={isFullScreen}
      />
      <audio
        onCanPlay={canplay}
        onError={handleError}
        onEnded={handleEnd}
        onTimeUpdate={handleTimeUpdate}
        ref={audioRef}
      />
    </div>
  );
};

export default memo(Player);
